<?php
App::uses('AppModel', 'Model');
/**
 * User Model
 *
 * @property UserBuyProduct $UserBuyProduct
 */
class User extends AppModel {

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'user_name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'between' => array(
				'rule' => array('between', 5, 20),
				'message' => 'user name between 5 and 20',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'balance' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'positive' => array(
				'rule' => array('validbalance'),
				'message' => 'balance must greater than 0'
				)
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * hasMany associations
 *
 * @var array
 */
	public $hasMany = array(
		'UserBuyProduct' => array(
			'className' => 'UserBuyProduct',
			'foreignKey' => 'user_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	public function validbalance($data) {
		return ($data['balance'] >= 0);
	}
	
	public function sub_balance($userId, $price, $transactionFlag = false) {
		$userInfo = $this->read(null, $userId);
		
		if (empty($userInfo)) {
			return 0;
		}

		$dataSouce = $this->getDataSource();
		
		// Truong hop su dung transaction
		if ($transactionFlag) {	
			$dataSouce->begin();
		}
		
		$result = $this->save(array(
			'id' => $userId,
			'balance' => $userInfo['User']['balance'] - $price
			));
			
		// Truong hop su dung Transaction
		if ($transactionFlag) {
			if ($result) {
				$dataSouce->commit();
			} else {
				$dataSouce->rollback();
			}
		}
		
		return $result;
	}
}
